package com.unionftech.content_login.ui.login

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.transition.TransitionManager
import android.view.KeyEvent
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.unionftech.common.R.color
import com.unionftech.common.R.drawable
import com.unionftech.common.R.string
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ApiException
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.bean.toastTimeout
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.recaptcha.RecaptchaUtil
import com.unionftech.common.router.RouterPath
import com.unionftech.common.router.service.ILoginService
import com.unionftech.common.utils.ActivityCollector
import com.unionftech.common.utils.ChangeDevUtil
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.SignUtils
import com.unionftech.common.utils.SpUtils
import com.unionftech.common.utils.StatusBarUtil
import com.unionftech.common.utils.ToastUtils
import com.unionftech.content_login.R
import com.unionftech.common.common.adapter.CommonFragmentStateAdapter
import com.unionftech.common.common.bean.CountryInfo
import com.unionftech.content_login.bean.LoginLockWarning
import com.unionftech.content_login.bean.LoginTokenInfo
import com.unionftech.content_login.bean.toastLockWarning
import com.unionftech.content_login.bean.toastRemoteWarning
import com.unionftech.content_login.contract.LoginContract
import com.unionftech.content_login.presenter.LoginPresenter
import com.unionftech.content_login.service.LoginConstants
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.content_login.ui.register.UFRegisterActivity


@Route(
    path = RouterPath.LoginActivityInfo.PATH, name = RouterPath.LoginActivityInfo.NAME
)
class UFLoginActivity : BaseMvpActivity(), LoginContract.ILoginView, IUpdate {
    private val mTvNewUser: TextView by lazy { mRootView.findViewById(R.id.tv_new_user) }
    private val mTvLoginTitle: TextView by lazy { mRootView.findViewById(R.id.tv_login_title) }
    private val mTvGotoRegister: TextView by lazy { mRootView.findViewById(R.id.tv_goto_register) }
    private val mTabLayout: TabLayout by lazy { mRootView.findViewById(R.id.tab_layout) }
    private val mViewPager: ViewPager2 by lazy { mRootView.findViewById(R.id.view_pager) }
    private val mFlGoogleLogin by lazy { mRootView.findViewById<FrameLayout>(R.id.fl_google_login) }
    private val mTvOtherLoginTitle by lazy { mRootView.findViewById<TextView>(R.id.tv_other_login_title) }
    private val mLlOtherLoginContainer by lazy { mRootView.findViewById<LinearLayout>(R.id.ll_other_login_content) }

    private lateinit var mFragments: List<BaseFragment>
    private lateinit var mTitles: List<String>
    private lateinit var mAdapter: CommonFragmentStateAdapter
    private lateinit var mEmailLoginFragment: EmailLoginFragment
    private lateinit var mPhoneLoginFragment: PhoneLoginFragment
    private var mPublicKeyStr: String = ""
    private var mShowBackBtn = false
    private var mInitIndex = 1
    private var mObserver: OnGlobalLayoutListener? = null
    private var mInitEmail: String? = null
    private var mInitPhone: String? = null
    private var mInitCountryInfo: CountryInfo? = null

    @InjectPresenter
    private lateinit var mLoginPresenter: LoginPresenter


    @Autowired
    @JvmField
    var mLoginService: ILoginService? = null

    init {
        ARouter.getInstance().inject(this)
    }

    companion object {
        private const val TAG = "UFLoginActivity"
        private const val PARAMS_CAN_RETURN_BACK = "canReturnBack"
        private const val PARAMS_INIT = "params_init"
        private const val PARAMS_INIT_EMAIL = "params_init_email"
        private const val PARAMS_INIT_PHONE = "params_init_phone"
        private const val PARAMS_INIT_COUNTRY_INFO = "params_init_country_info"


        @JvmStatic
        fun startThis(context: Context) {
            val intent = Intent(context, UFLoginActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            intent.putExtra(PARAMS_INIT_PHONE, "")
            intent.putExtra(PARAMS_INIT_EMAIL, "")
            context.startActivity(intent)
        }

        @JvmStatic
        fun startThis(context: Context, canReturnBack: Boolean) {
            val intent = Intent(context, UFLoginActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            intent.putExtra(PARAMS_INIT_PHONE, "")
            intent.putExtra(PARAMS_INIT_EMAIL, "")
            intent.putExtra(PARAMS_CAN_RETURN_BACK, canReturnBack)
            context.startActivity(intent)
        }

        /**
         * 跳转邮箱登录
         */
        @JvmStatic
        fun startThis(context: Context, email: String) {
            val intent = Intent(context, UFLoginActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            intent.putExtra(PARAMS_INIT_EMAIL, email)
            intent.putExtra(PARAMS_INIT, 0)
            context.startActivity(intent)
        }

        /**
         * 跳转手机号登录
         */
        @JvmStatic
        fun startThis(context: Context, countryInfo: CountryInfo, phone: String) {
            val intent = Intent(context, UFLoginActivity::class.java)
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            intent.putExtra(PARAMS_INIT, 1)
            intent.putExtra(PARAMS_INIT_COUNTRY_INFO, countryInfo)
            intent.putExtra(PARAMS_INIT_PHONE, phone)
            context.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initLayout() = R.layout.activity_uflogin

    override fun initData() {
        super.initData()
        mEmailLoginFragment = EmailLoginFragment.newInstance(mInitEmail)
        mPhoneLoginFragment = PhoneLoginFragment.newInstance(mInitCountryInfo, mInitPhone)
        mFragments = listOf(mEmailLoginFragment, mPhoneLoginFragment)
        mTitles = listOf(
            DynamicResourceManager.getString(mContext, string.email),
            DynamicResourceManager.getString(mContext, string.phone)
        )
        mAdapter = CommonFragmentStateAdapter(this)
        mAdapter.addFragment(mFragments)
    }


    override fun obtainIntentData(intent: Intent) {
        super.obtainIntentData(intent)
        mShowBackBtn = intent.getBooleanExtra(PARAMS_CAN_RETURN_BACK, false)
        mInitIndex = intent.getIntExtra(PARAMS_INIT, 1)
        mInitEmail = intent.getStringExtra(PARAMS_INIT_EMAIL) ?: ""
        mInitPhone = intent.getStringExtra(PARAMS_INIT_PHONE) ?: ""
        mInitCountryInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(PARAMS_INIT_COUNTRY_INFO, CountryInfo::class.java)
        } else {
            intent.getParcelableExtra(PARAMS_INIT_COUNTRY_INFO)
        }
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvLoginTitle.text = DynamicResourceManager.getString(mContext, string.log_in)
        mTvGotoRegister.text = DynamicResourceManager.getString(mContext, string.sign_up)
        mTvNewUser.text = DynamicResourceManager.getString(mContext, string.new_user_title)
        mTvOtherLoginTitle.text = DynamicResourceManager.getString(mContext, string.or_sign_with)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (::mEmailLoginFragment.isInitialized) {
            mEmailLoginFragment.setInitEmail(mInitEmail)
            mEmailLoginFragment.resetPasswordData()
        }
        if (::mPhoneLoginFragment.isInitialized) {
            mInitCountryInfo?.also {
                mPhoneLoginFragment.setCountryInfo(it)
            }
            mPhoneLoginFragment.setPhone(mInitPhone)
            mPhoneLoginFragment.resetPasswordData()
        }
        mViewPager.setCurrentItem(mInitIndex, false)
    }

    override fun setListener() {
        super.setListener()
        mTvGotoRegister.setOnClickListener(this)
        mFlGoogleLogin.setOnClickListener(this)
        mEmailLoginFragment.setLoginListener(::requestLogin)
        mPhoneLoginFragment.setLoginListener(::requestLogin)
        mTvLoginTitle.setOnClickListener {
            ChangeDevUtil.changeDev(mActivity)
        }
        mObserver = OnGlobalLayoutListener {
            mViewPager.viewTreeObserver.removeOnGlobalLayoutListener(mObserver)
            mViewPager.setCurrentItem(mInitIndex, false)
            getPublicKey()
            getCountryInfoByIp()
        }
        mViewPager.viewTreeObserver.addOnGlobalLayoutListener(mObserver)
    }

    override fun statusBar() {
        StatusBarUtil.immersive(this)
        StatusBarUtil.setNavbarColor(
            this, mContext.getColor(color.color_white)
        )
        StatusBarUtil.darkMode(this, false)
    }


    private fun initTitleBar() {
        hideCenterTitle()
        if (mShowBackBtn) {
            showBackImg(drawable.ic_title_back_white)
        } else {
            hideBackImg()
        }
        setRightImg(drawable.ic_headphones_white) {
            //TODO:正在开发
            ToastUtils.longToast(
                DynamicResourceManager.getString(
                    mContext, string.developing
                )
            )
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish()
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun backPressed(): Boolean {
        if (mShowBackBtn) {
            finish()
            return true
        }
        return false
    }

    override fun setView() {
        super.setView()
        initTitleBar()
        mRootView.setBackgroundResource(R.drawable.ic_login_bg)
        val textPaint = mTvGotoRegister.paint
        textPaint.flags = Paint.UNDERLINE_TEXT_FLAG //下划线
        textPaint.isAntiAlias = true //抗锯齿
        mViewPager.adapter = mAdapter
        mViewPager.offscreenPageLimit = 1
        TabLayoutMediator(mTabLayout, mViewPager) { tab, position ->
            tab.text = mTitles[position]
        }.attach()
        loadData()
    }

    override fun loadData() {
        super.loadData()
    }

    private fun getCountryInfoByIp() {
        val countryInfo = GlobalInfoManager.getInstance().getCountryInfo()
        if (countryInfo != null) {
            updateCountryInfoByIp(countryInfo)
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_COUNTRY_INFO)
        }
    }

    private fun getPublicKey() {
        val publicKeyStr = GlobalInfoManager.getInstance().getPublicKeyStr()
        if (!TextUtils.isEmpty(publicKeyStr)) {
            mPublicKeyStr = publicKeyStr
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_PUBLIC_KEY)
        }
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.tv_goto_register -> UFRegisterActivity.startThis(mActivity)
            R.id.fl_google_login -> mLoginService?.gotoGoogleLogin()
        }
    }

    private fun requestLogin(account: String, password: String) {
        //密码加密
        SignUtils.encrypt(
            SignUtils.loadPublicKeyByStr(mPublicKeyStr), password.toByteArray()
        )?.also { encryptPassword ->
            mLoginPresenter.login(account, encryptPassword)
        } ?: ToastUtils.longToast(
            DynamicResourceManager.getString(mContext, string.login_failed)
        )
    }


    override fun handleLoginResult(response: ResponseResult<Any?>) {
        when (response.code) {
            //登录成功(1.登录成功 2.异地异常登录成功)
            ResponseResult.SUCCESS_CODE, LoginConstants.Code.REMOTE_LOGIN_WARNING -> {
                //异地登录异常提醒
                if (response.code == LoginConstants.Code.REMOTE_LOGIN_WARNING) {
                    response.data?.also { data ->
                        (data as LoginTokenInfo).toastRemoteWarning()
                    }
                }
                gotoMain()
            }
            //密码错误提醒
            LoginConstants.Code.LOGIN_LOCK_WARNING -> {
                response.data?.also {
                    val loginLockWarning = it as LoginLockWarning
                    loginLockWarning.toastLockWarning()
                }
            }

            else -> {
                if (ApiException.isTimeout(response.code)) {
                    response.toastTimeout()
                } else if (response.code != ResponseResult.CANCEL_CODE) {
                    response.toast(
                        DynamicResourceManager.getString(
                            mContext, string.login_failed
                        )
                    )
                }
                LogUtils.e(
                    TAG, "handleLoginResult error code:${response.code} msg:${response.msg}"
                )
            }
        }
    }

    private fun gotoMain() {
//        SpUtils.getInstance()
//            .put(LoginConstants.Key.LOGIN_WAY, LoginConstants.Constant.LOGIN_BY_ACCOUNT)
        ARouter.getInstance().build(RouterPath.UFUFMainStandardActivityInfo.PATH).navigation()
        ActivityCollector.finishAll()
    }

    override fun onUpdate(obj: Any?) {
        when (obj) {
            is String -> {
                mPublicKeyStr = obj
            }

            is CountryInfo -> {
                updateCountryInfoByIp(obj)
            }
        }
    }

    private fun updateCountryInfoByIp(countryInfo: CountryInfo) {
        setShowOtherLoginWay(countryInfo.code != LoginConstants.Constant.CHINA_CODE)
        if (::mPhoneLoginFragment.isInitialized) {
            mPhoneLoginFragment.setCountryInfo(countryInfo)
        }
    }

    private fun setShowOtherLoginWay(show: Boolean) {
        // 开始过渡动画
        TransitionManager.beginDelayedTransition(mRootView)
        LogUtils.d(TAG, "setShowOtherLoginWay  show-->$show")
        if (show) {
            mLlOtherLoginContainer.visibility = View.VISIBLE
        } else {
            mLlOtherLoginContainer.visibility = View.GONE
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mAdapter.getFragment(mViewPager.currentItem)
            ?.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        RecaptchaUtil.getInstance().destroy()
        super.onDestroy()
    }


}